<script setup lang="ts">
import { fetchRecordDetails, type LogDataRecord } from '@/api/admin/historyRecord'
import { rate } from '@/api/admin/public'
import userAvatar from '@/assets/user-avatar.png'
import aiAvatar from '@/assets/ai-avatar.png'

const router = useRouter()

const query = (useRoute().query || {
  medical_record_number: '',
  created_date: '',
}) as {
  medical_record_number: string
  created_date: string
}

const rateResult = ref()

const recordDetails = ref<LogDataRecord | null>(null)

// 对话项接口定义
interface ConversationItem {
  role: 'user' | 'assistant'
  content: string
}

// 解析后的对话历史记录
const conversations = ref<ConversationItem[]>([])

const getRecordDetails = async () => {
  try {
    const response = await fetchRecordDetails(query.medical_record_number, query.created_date)
    if (response) {
      recordDetails.value = response
      if (recordDetails.value?.speech_analysis?.['dialogue.jsonl']) {
        const url =
          `http://localhost:8000/${recordDetails.value.speech_analysis['dialogue.jsonl']}`.replace(
            /\\+/g,
            '/',
          )
        fetchChatRecord(url)
      } else {
        ElMessage.warning('未找到聊天记录')
      }
    }
  } catch (error: any) {
    ElMessage.error(error?.errorDetails.description || error?.message || '未知错误')
  }
}

const chatRecord = ref()

const fetchChatRecord = async (url: string) => {
  try {
    const response = await fetch(url)
    if (response.ok) {
      const text = await response.text()
      const lines = text.trim().split('\n')
      const parsedConversations: ConversationItem[] = []

      lines.forEach((line) => {
        if (line.trim()) {
          try {
            const data = JSON.parse(line)
            // 处理用户消息
            if (data.user && data.user.content) {
              const userContent = data.user.content.trim()
              if (userContent) {
                parsedConversations.push({
                  role: 'user',
                  content: userContent,
                })
              }
            }
            // 处理助手回复
            if (data.assistant_response && Array.isArray(data.assistant_response)) {
              data.assistant_response.forEach((response: any) => {
                if (response.role === 'assistant' && response.content) {
                  parsedConversations.push({
                    role: 'assistant',
                    content: response.content.trim(),
                  })
                }
              })
            }
          } catch (parseError) {
            console.error('解析JSON行失败:', parseError)
          }
        }
      })

      conversations.value = parsedConversations
      chatRecord.value = { conversations: parsedConversations }
    }
  } catch (error: any) {
    ElMessage.error('获取聊天记录失败')
    console.error('获取聊天记录失败: ', error)
  }
}

const question = ref<Record<string, string>>({})

const fechQuestion = async () => {
  try {
    const response = await fetch('http://localhost:8000/static/speech.json')
    if (response.ok) {
      question.value = await response.json()
    }
  } catch (error: any) {
    ElMessage.error('获取评分失败')
    console.error('获取评分失败: ', error)
  }
}

const handleSubmit = async () => {
  if (!rateResult.value && rateResult.value !== 0) {
    ElMessage.warning('请先选择评分')
    return false
  }
  try {
    await rate({
      medical_record_number: query.medical_record_number,
      created_date: query.created_date,
      category: 'speech_analysis',
      score: rateResult.value,
    })
    router.push({
      path: '/singleRecord',
      query: {
        medical_record_number: query.medical_record_number,
      },
    })
  } catch (error) {
    ElMessage.error('评分失败')
    console.error('评分失败: ', error)
  }
}

const handleBack = () => {
  router.push({
    path: '/speech',
    query: {
      medical_record_number: query.medical_record_number,
      created_date: query.created_date,
    },
  })
}

onMounted(() => {
  fechQuestion()
  getRecordDetails()
})
</script>

<template>
  <el-row :gutter="48" class="h-full -mr-6">
    <el-col :span="12" class="h-full overflow-hidden">
      <!-- 聊天记录区域 -->
      <div class="h-full flex flex-col bg-gray-50 p-4">
        <div class="text-brand text-xl font-semibold mb-4 border-b border-gray-200 pb-2">
          语音交互记录
        </div>

        <!-- 对话历史 -->
        <div class="flex-1 overflow-y-auto space-y-4">
          <div v-if="conversations.length === 0" class="text-center text-gray-500 py-8">
            暂无聊天记录
          </div>

          <div
            v-for="(conversation, index) in conversations"
            :key="index"
            class="flex items-start gap-3"
            :class="conversation.role === 'user' ? 'justify-end' : 'justify-start'"
          >
            <!-- AI头像 -->
            <img
              v-if="conversation.role === 'assistant'"
              :src="aiAvatar"
              class="w-8 h-8 rounded-full flex-shrink-0"
              alt="AI"
            />

            <!-- 消息内容 -->
            <div
              class="max-w-3/4 px-4 py-2 rounded-lg text-sm whitespace-pre-wrap"
              :class="
                conversation.role === 'user'
                  ? 'bg-blue-500 text-white rounded-br-none'
                  : 'bg-white text-gray-800 rounded-bl-none border border-gray-200'
              "
            >
              {{ conversation.content }}
            </div>

            <!-- 用户头像 -->
            <img
              v-if="conversation.role === 'user'"
              :src="userAvatar"
              class="w-8 h-8 rounded-full flex-shrink-0"
              alt="User"
            />
          </div>
        </div>
      </div>
    </el-col>
    <el-col :span="12" class="h-full overflow-auto pr-6">
      <div class="text-brand text-2xl">当前结果：</div>
      <div class="text-#00BA3D font-500 mt-4">
        <span class="text-4xl">{{ rateResult || 0 }}</span>
        <span class="text-lg ml-1">分</span>
      </div>
      <div class="text-brand text-lg mt-4">{{ question[rateResult] || '' }}</div>
      <div class="text-#0167bc text-2xl mt-12">结果修改：</div>
      <el-radio-group v-model="rateResult" class="mt-4">
        <el-radio v-for="rate in Object.keys(question)" :key="rate" :value="Number(rate)">
          {{ question[rate] }}
        </el-radio>
      </el-radio-group>
      <div class="flex items-center justify-evenly gap-8 mt-12">
        <el-button type="primary" class="flex-1" @click="handleSubmit">提交结果</el-button>
        <el-button class="brand-dark-button flex-1" @click="handleBack">返回上一页</el-button>
      </div>
    </el-col>
  </el-row>
</template>

<style lang="css" scoped>
:deep(.el-radio) {
  display: block;
  width: 100%;
}
:deep(.el-radio) {
  --el-color-primary: #508bcc;
  --el-radio-font-size: 16px;
  margin-bottom: 8px;
}
:deep(.el-button) {
  padding: 18px 0;
}
</style>
